import pymongo
import time
from config import *
conn = pymongo.Connection(host=MONGO_HOST,port=MONGO_PORT)
mongo = conn.temp

class TempCache:
    def __init__(self):
        self.collection = mongo.tmp
        pass
    
    def get(self,key):
        ret = self.collection.find_one({"key":key})
        if(ret):
            return ret["value"]
        else:
            return None
        
    def delete(self,key):
        ret = self.collection.remove({"key":key})
        return ret
        
    def set(self,key,value,expire = 0):
        ret = self.collection.find({"key":key}).count()
        if(expire > 0):
            expire = int(time.time()) + expire
            pass
        if(ret > 0):
            ret = self.collection.update({"key":key},{"$set":{"value":value,"expire":expire}})
            pass
        else:
            ret = self.collection.insert({"key":key,"value":value,"expire":expire})
            pass
        
        return ret